<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="120px"
    >
      <el-row>
        <el-col :span="16">
          <el-form-item label="考评任务名称" prop="provinceId">
            <el-select
              v-model="queryParams.name"
              placeholder="请选择考评任务名称"
              filterable
              :disabled="isTableEdit"
              clearable
              @change="changeKpk"
              style="width: 400px"
            >
              <el-option
                v-for="item in optionTaskData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="buttonStyle">
          <el-button type="primary" @click="handleArea" v-if="isShowArea == 0 && active == 0 && mark">面积占比计算</el-button>
          <el-button type="primary" @click="handleArea" v-if="isShowArea == 1 && isMulTask">面积占比查看</el-button>
          <el-button type="primary"  @click="handleSystemScore" v-if="active == 0" :disabled="mark&&isShowArea==0">系统评分</el-button>
          <el-button plain @click="handleUpdate" v-if="active == 0">修改</el-button>
          <el-button type="primary" @click="handleDistribute" v-if="active == 1">分发</el-button>
          <el-button type="primary" @click="handleStopScore" v-if="active == 2">停止评分</el-button>
          <el-button type="primary" @click="handleRanking" v-if="active == 3">排名预览及修改</el-button>
          <el-button plain @click="delData" v-if="active != 4">删除</el-button>
          <el-button plain @click="submitData" v-if="active == 0">保存</el-button>
        </el-col>
      </el-row>
    </el-form>
    <span class="tab-title">考评任务信息</span>
    <el-form
      ref="ruleForm"
      :model="form"
      label-width="140px"
      :rules="rules"
      label-position="left"
    >
      <p class="mt15"></p>
      <el-row>
        <el-col :span="10">
          <el-form-item label="考评任务名称:" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入考评任务名称"
              :disabled="!isTableEdit"
              show-word-limit
              clearable
              style="width: 400px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="考评库:" prop="kesdId">
            <el-select
              v-model="form.kesdId"
              placeholder="请选择考评库名称"
              filterable
              clearable
              :disabled="!isTableEdit"
              style="width: 400px"
            >
              <el-option
                v-for="item in optionData"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="考评任务环节">
            <span v-if="active == 0">新建</span>
            <span v-if="active == 1">系统评分</span>
            <span v-if="active == 2">专家评分</span>
            <span v-if="active == 3">排名确认</span>
            <span v-if="active == 4">排名发布</span>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="专家评分小组:" prop="expertGroupId">
            <el-input
              v-model="form.expertGroupId"
              placeholder="请选择小组"
              :disabled="!isTableEdit"
              readonly
              @click="groupDialog"
              clearable
              style="width: 400px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="专家评分截止日期:" prop="endDate">
            <el-date-picker
              clearable
              :disabled="!isTableEdit"
              v-model="form.endDate"
              type="date"
              style="width: 400px"
              value-format="YYYY-MM-DD"
              placeholder="提醒专家评分的截止日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span class="tab-title">考评任务进度</span>
    <steps :datas="forms.progressList" />
    <span class="tab-title">关联任务</span>
    <!-- 新建阶段 -->
    <createSchedule  v-if="active == 0" :forms="forms" :isTableEdit="isTableEdit" ref="formsRef" />
    <!-- 系统评分阶段 -->
    <systemSchedule :forms="forms" v-if="active == 1" :krtId="queryParams.name" @refreshList="refreshList" />
    <!-- 专家评分阶段 -->
    <expertScore :forms="forms" v-if="active == 2" :krtId="queryParams.name" />
    <!-- 排名确认和排名发布阶段 -->
    <RankingConfirmation  :forms="forms" v-if="active == 3 || active == 4" :activeData="active" :krtId="queryParams.name" />
    <!-- 面积占比 -->
    <el-dialog :title="isShowArea == 0 ? '面积占比计算' : '面积占比查看'" v-model="open" width="800px" append-to-body>
      <el-button type="primary" v-if="isShowArea == 0"  @click="startAreaOperation" class="countBtn">
        计算
      </el-button>
      <areaOperation :areaOperationList="areaOperationList" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitArea" v-if="isShowArea=='0'">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配小组 -->
    <el-dialog
      title="分配小组"
      v-model="openGroup"
      width="900px"
      append-to-body
    >
      <p class="dialogTitle">分配小组</p>
      <el-form
        ref="groupRef"
        :model="formDialog"
        label-width="80px"
        :inline="true"
        class="addGroup"
      >
        <el-form-item label="小组名称" prop="groupName">
          <el-input
            v-model="formDialog.groupName"
            placeholder="请输入小组名称"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="小组组长" prop="groupLeader">
          <el-input
            v-model="formDialog.groupLeader"
            placeholder="请输入小组组长"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 分配小组 -->
      <el-table v-loading="loading" :data="groupList" stripe row-key="id">
        <!-- <el-table-column type="selection" width="55" align="center" :reserve-selection="true" /> -->
        <el-table-column label="小组名称" align="center" prop="groupName" />
        <el-table-column label="小组组长" align="center" prop="groupLeader" />
        <el-table-column
          label="小组组员"
          align="center"
          prop="groupMember"
          show-overflow-tooltip
        />
        <el-table-column
          label="专家成员"
          align="center"
          prop="groupExpert"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button type="text" @click="handleAllocation(scope.row)"
              >分配</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="formDialog.page"
        v-model:limit="formDialog.rows"
        @pagination="getGroupList"
      />
    </el-dialog>
    <el-dialog
      title="系统评分"
      v-model="SystemOpen"
      width="800px"
      append-to-body
    >
      <div class="systemBox"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="systemSumit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="appraisalTaskManage">
import { dataMethod } from "@/utils/spanTable.js";
import { getGroup } from "@/api/taskmanage/group.js";
import {
  kpRatingTaskList,
  kpRatingTaskGetById,
  systemScoreOps,
  areaProportionOperation,
  getAreaRadio,
  getSystemScoreOpsing,
  updateKpTask,
  deleteKpTask,
  distributionKpTask2Expert,
  getExpertByKrtId,
  stopTask,
} from "@/api/workEvaluation/appraisalTaskManagement/appraisalTaskManage.js";
import { getAllAppraisal } from "@/api/workEvaluation/evaluationStandardSetup/appraisalDatabaseManage.js";
import steps from "../components/steps";
import createSchedule from "../components/createSchedule";
import systemSchedule from "../components/systemSchedule";
import expertScore from "../components/expertScore";
import RankingConfirmation from "../components/RankingConfirmation";
import areaOperation from "../components/areaOperation";
import { useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const router = useRouter();
const optionData = ref([]);
const optionTaskData = ref([]);
const isShowArea = ref(0);
const parameter = ref({});
const isTableEdit = ref(false);
const openGroup = ref(false);
const loading = ref(true);
const open = ref(false); //面积占比模态框
const SystemOpen = ref(false); //系统评分模态框
const spanObj = ref();
const active = ref(0);
const total = ref(0);
const mark = ref(false);//面积占比计算按钮
const expertNames = ref("");
const formsRef = ref(null)
const data = reactive({
  queryParams: {
    page: 1,
    rows: 10,
    name: "",
  },
  form: {},
  forms: {
    dataList: [],
    page: 1,
    rows: 10,
  },
  groupList: [],
  areaOperationList: [],
  formDialog: {
    page: 1,
    rows: 10,
    groupName: undefined,
    groupLeader: undefined,
    groupMember: undefined,
    groupExpert: undefined,
  },
});
const { queryParams, form, forms, areaOperationList, groupList, formDialog } =
  toRefs(data);
  const rules = ref({
    name: [
    { required: true, message: "请输入考评任务名称", trigger: "blur" },
  ],
  kesdId: [{ required: true, message: "请选择考评库名称", trigger: "change" }],
  expertGroupId: [
    { required: true, message: "请选择专家评分小组", trigger: "change" },
  ],
  endDate: [{ required: true, message: "请选择截止日期", trigger: "change" }],
});
watch(
  () =>areaOperationList.value,
  () => {
    spanObj.value = dataMethod(areaOperationList.value, ["provinceName"]);
  }
);
const appraisalList = () => {
  getAllAppraisal()
    .then((res) => {
      if (res.data && res.data.length > 0) {
        optionData.value = res.data;
      }
      getData();
    })
    .catch((err) => {});
};

// 面积占比表格合并
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  //判断合并列
  // console.log(column)
  const _row = spanObj.value[column.property]
    ? spanObj.value[column.property][rowIndex]
    : 1;
  const _col = _row > 0 ? 1 : 0;
  return {
    rowspan: _row,
    colspan: _col,
  };
}
const submitFormSelect = () => {};
const changeKpk = (val) => {
  if (val) {
    queryParams.value.name = val;
    getListData();
  } else {
    dataList.value = [];
  }
};
// 修改
const handleUpdate = () => {
  isTableEdit.value = true;
};
/** 查询小组列表 */
function getGroupList() {
  loading.value = true;
  getGroup(formDialog.value).then((response) => {
    groupList.value = response.data.result;
    total.value = response.data.total;
    loading.value = false;
  });
}
//选择小组
const groupDialog = () => {
  openGroup.value = true;
  formDialog.value.groupName=''
  formDialog.value.groupLeader=''
  formDialog.value.page = 1;
  getGroupList();
};
const handleQuery = () => {
  getGroupList();
};
const handleReset = () => {
  proxy.resetForm("groupRef");
  handleQuery();
};
//分配
const handleAllocation = (val) => {
  form.value.expertGroupId = val.groupName;
  form.value.groupId = val.id;
  openGroup.value = false;
};
// 面积占比
const handleArea = () => {
  open.value = true;
  searchProvince();
};
const searchProvince = () => {
  getAreaRadio({
    kryId: queryParams.value.name,
  }).then((res) => {
    areaOperationList.value = res.data;
  });
};
//点击计算 计算面积占比
const startAreaOperation = () => {
  areaProportionOperation({ krtId: queryParams.value.name }).then((res) => {
    areaOperationList.value = res.data;
    appraisalList();
  });
};
//面积占比点击确认
const submitArea = () => {
  open.value = false;
  appraisalList();
};
// 系统评分
const handleSystemScore = () => {
  systemScoreOps({ krtId: queryParams.value.name }).then((res) => {
    if (res.code == 200) {
      startSystemScore();
    }
  });
  SystemOpen.value = true;
};
// 系统评分开始计算
const startSystemScore = () => {
  let box = document.getElementsByClassName("systemBox")[0];
  let startTime = setInterval(() => {
    let str = "";
    getSystemScoreOpsing({ krtId: queryParams.value.name }).then((res) => {
      res.data.forEach((v, i) => {
        str += `<p>` + v + `</p>`;
      });
      box.innerHTML = str;
      if (res.data.includes("计算完成")) {
        clearInterval(startTime);
      }
    });
  }, 500);
};
const systemSumit = () => {
  SystemOpen.value = false;
  getListData();
};
const refreshList=()=>{
  getListData()
}
// 排名预览
const handleRanking = () => {
  router.push({
    path: "/workEvaluation/appraisalTaskManagement/rankingPreview",
    query: {
      metaTitle: "排名预览",
      krtId: queryParams.value.name,
    },
  });
};
// 保存
const submitData = () => {
  proxy.$refs["queryRef"].validate((valid) => {
    if (valid) {
      proxy.$refs['ruleForm'].validate((valid)=>{
        if(valid){
          nextTick(()=>{
            formsRef.value.$refs['formRef'].validate((valid)=>{
              if(valid){
                let taskList = JSON.parse(JSON.stringify(forms.value.dataList));
                form.value.expertGroupName = form.value.expertGroupId;
                form.value.expertGroupId = form.value.groupId;
                let obj = {
                  kpTaskId: queryParams.value.name,
                  ...form.value,
                  taskList,
                };
                updateKpTask(obj).then((res) => {
                  if (res.code == 200) {
                    proxy.$modal.msgSuccess("保存成功");
                    isTableEdit.value = false;
                    appraisalList();
                  }
                });
              }
            })
          })
        }
      })
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};
const delData = () => {
  proxy.$modal
    .confirm("是否确认删除该数据项？")
    .then(function () {
      deleteKpTask({ krtId: queryParams.value.name }).then((res) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess("删除成功");
          appraisalList();
        }
      });
    })
    .catch(() => {});
};
// 分发
const handleDistribute = () => {
  getExpertByKrtId({ krtId: queryParams.value.name }).then((res) => {
    if (res.code == 200) {
      expertNames.value = res.data;
      const confirmMessage =
        `请确认是否将考评任务分发给以下专家评分` + expertNames.value;
      proxy.$modal
        .confirm(confirmMessage, "系统提示", {
          confirmButtonText: "确认分发",
          type: "warning",
        })
        .then((res) => {
          distributionKpTask2Expert({ krtId: queryParams.value.name }).then(
            (res) => {
              if (res.code == 200) {
                proxy.$modal.msgSuccess("分发成功");
                appraisalList();
              }
            }
          );
        })
        .catch((err) => {});
    }
  });
};
// 停止评分
const handleStopScore = () => {
  stopTask({ krtId: queryParams.value.name }).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("停止评分成功");
      appraisalList();
    }
  });
};
// 查询考评任务列表接口
const getData = () => {
  kpRatingTaskList().then((res) => {
    if (res.code == 200) {
      optionTaskData.value = res.data;
      if (res.data[0]) {
        queryParams.value.name = res.data[0].id;
      } else {
        queryParams.value.name = "";
      }
      getListData();
    }
  });
};
// 一个省有多个任务
let isMulTask = ref(false);
const getListData = () => {
  proxy.$modal.loading()
  kpRatingTaskGetById({ krtId: queryParams.value.name }).then((res) => {
    proxy.$modal.closeLoading();
    if (res.data) {
      parameter.value = res.data;
      form.value.name = res.data.name;
      form.value.kesdId = res.data.kesdId;
      form.value.expertGroupId = res.data.expertGroupName;
      form.value.endDate = res.data.endDate;
      forms.value.dataList = res.data.taskList;
      forms.value.areaList = res.data.areaList;
      forms.value.progressList = res.data.progressList;
      active.value = res.data.progressList[0].status;
      isShowArea.value = res.data.isRunAreaRatio;
      mark.value = res.data.showOrNot;
      isMulTask.value = forms.value.areaList?.some(item => item.ypgTaskNames?.split('、').length > 1) || forms.value.dataList?.some(item => item.ypgName?.split('、').length > 1)
    }
  }).catch(err=>{
    proxy.$modal.closeLoading();
  });
};
onMounted(() => {
  spanObj.value = dataMethod(areaOperationList.value, ["provinceName"]);
  appraisalList();
});
</script>

<style scoped lang="scss">

:deep(.el-table).borderTable td.el-table__cell {
  border-bottom: 1px solid #ebeef5 !important;
  border-right: 1px solid #ebeef5 !important;
  .cell {
    // height: 60px;
    // line-height: 60px;
    .el-form-item {
      position: relative;
      top: 18px;
      .el-input__suffix {
        top: 9px;
      }
    }
  }
}
:deep(.el-table__append-wrapper) {
  text-align: center;
}
.borderTables {
  padding: 20px 0;
  box-sizing: border-box;
}
:deep(.el-table).borderTables td.el-table__cell {
  border-bottom: 1px solid #ebeef5 !important;
  border-right: 1px solid #ebeef5 !important;
  .cell {
    height: 68px;
    line-height: 68px;
    .el-form-item {
      position: relative;
      top: 18px;
      .el-input__suffix {
        top: 9px;
      }
    }
  }
}
.buttonStyle{
  text-align: right;
}
.systemBox {
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: space-between;
  p {
    width: 40%;
  }
}
.countBtn {
  margin: 20px 0 0px 0;
  box-sizing: border-box;
}
.tab-title {
  font-size: 18px;
  font-weight: bold;
  border-left: 4px solid var(--el-color-primary);
  font-family: PingFangSC-Medium;
  padding-left: 10px;
  margin-bottom: 20px;
  width: 100%;
  display: inline-block;
}
</style>
